package org.petstore.service.impl;

import org.petstore.domain.Account;
import org.petstore.persistence.UserDAO;
import org.petstore.persistence.impl.UserDAOImpl;
import org.petstore.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AccountServiceImpl implements AccountService {
    private final UserDAO userDAO = new UserDAOImpl();

    public AccountServiceImpl() {
    }

    public AccountServiceImpl(UserDAO userDAO) {

    }

    public static void main(String[] args) {
        System.out.println("123123123");
        new AccountServiceImpl().login("123","123");
    }

    @Override
    public Account getAccount(String username) {
        return userDAO.getUserInfoByUsername(username);
    }

    @Override
    public Account login(String username, String password) {
        ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDAO userDAO=(UserDAO)context.getBean("userDao");
        return userDAO.findUserByUsernameAndPassword(username, password);
    }

    /**
     * description 用于注册
     *
     * @param user:
     * @return int -1: 用户名已存在 0: 异常
     * @author huangzhangyan
     * @date 2021/11/1 1:37
     */
    @Override
    public int register(Account user) {
        if (user == null) {
            return 0;
        }
        if (isUsernameExist(user.getUsername())) {
            //用户名已存在，不能注册
            return -1;
        } else {
            userDAO.addUser(user);
            return 1;
        }
    }

    /**
     * description
     *
     * @param user:
     * @param currentUsername:
     * @return int -1 新用户名已被占用
     * @author huangzhangyan
     * @date 2021/11/1 1:41
     */
    @Override
    public int editAccountIncludeUsername(Account user, String currentUsername) {
        if (isUsernameExist(user.getUsername())) {
            //新用户名存在
            if (user.getUsername().equals(currentUsername)) {
                //是自己的用户名
                userDAO.deleteUser(currentUsername);
                userDAO.addUser(user);
                return 1;
            }
            //不是自己的用户名
            //新用户名已被占用
            return -1;
        }
        //新用户名不存在
        userDAO.deleteUser(currentUsername);
        userDAO.addUser(user);
        return 1;
    }

    /**
     * description 用户名是否存在
     *
     * @param username:
     * @return boolean
     * @author huangzhangyan
     * @date 2022/1/10 15:37
     */
    @Override
    public boolean isUsernameExist(String username) {
        return userDAO.isUserExistByUsername(username);
    }

}
